package com.ohc.leetcode.数组.repect;


import com.sun.org.apache.bcel.internal.generic.I2F;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2022年8月28日16:42:57
 */
public class 两数之和1 {
    public static void main(String[] args) {
        int[] nums = new int[]{2, 7, 11, 15};
//         9-2
//         9-2 判断需要的那个数字map里有没有
//         如果算出来刚好that的索引为1 和当前遍历的索引i一样的话
        int[] ints = twoSum03(nums, 9);
        for (int anInt : ints) {
            System.out.println("anInt = " + anInt);
        }
    }

    public static int[] twoSum01(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }

        }
        return new int[]{};
    }

    //             O（n）
    public static int[] twoSum02(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {  // 遍历整个数组获取索引和值的对应关系  key 是值
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int thatNum = target - nums[i];
            // !=i 是为了防止 [3,2,4]
            //6   出现2个0  map.get(thatNum) 然后对应的i也为0
            if (map.containsKey(thatNum) && map.get(thatNum) != i) {
                return new int[]{map.get(thatNum), i};
            }

        }
        return new int[]{};
    }


    public static int[] twoSum03(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int thatNum = target - nums[i];
            // !=i 是为了防止 [3,2,4]
            //6   出现2个0  map.get(thatNum) 然后对应的i也为0
            if (map.containsKey(thatNum) && map.get(thatNum) != i) {
                return new int[]{map.get(thatNum), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }

}
